package org.mat.sample.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 2 * @Author: lvdebo
 * 3 * @Date: 2021/8/14 3:36 下午
 * 4
 */
@Slf4j
//@Configuration
public class FeignClientInterceptor implements RequestInterceptor {
    public static final String CONTEXT_KEY = "CONTEXT_KEY";

        @Override
        public void apply(RequestTemplate requestTemplate) {
            Map<String,String> headers = getHeaders(getHttpServletRequest());
            for(String headerName : headers.keySet()){
                requestTemplate.header(headerName, getHeaders(getHttpServletRequest()).get(headerName));
            }
        }

        private HttpServletRequest getHttpServletRequest() {
            try {
                return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        private Map<String, String> getHeaders(HttpServletRequest request) {
            Map<String, String> map = new LinkedHashMap<>();
            Enumeration<String> enumeration = request.getHeaderNames();
            while (enumeration.hasMoreElements()) {
                String key = enumeration.nextElement();
                String value = request.getHeader(key);
                map.put(key, value);
            }
            return map;
        }

}
